package com.iaiai.cobra.web.controller;

import com.iaiai.cobra.common.util.Md5;
import com.iaiai.cobra.common.util.StringUtil;
import com.iaiai.cobra.common.vo.ResultVo;
import com.iaiai.cobra.core.BaseController;
import com.iaiai.cobra.repository.bean.Dept;
import com.iaiai.cobra.repository.bean.Post;
import com.iaiai.cobra.repository.bean.User;
import com.iaiai.cobra.web.params.ProfileEditPasswordParams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with ProfileController.
 * Package: com.iaiai.cobra.web.controller
 * Author: iaiai
 * Create Time: 2024/7/4 22:20
 * QQ: 176291935
 * Email: 176291935@qq.com
 * Description:
 */
@RestController
@RequestMapping("/profile")
public class ProfileController extends BaseController {

    @PostMapping("/detail.json")
    public ResultVo detail() throws IOException {
        User onlineUser = getOnline().getUser();

        Map<String,Object> map = new HashMap<>();
        User user = serviceManager.userService.getById(onlineUser.getId());
        map.put("user",user);

        List<Post> posts = serviceManager.postService.queryByUser(user.getId());
        List<Dept> depts = serviceManager.deptService.queryByUser(user.getId());

        map.put("posts",posts);
        map.put("depts",depts);

        return success(map);
    }

    @PostMapping("/edit/password.do")
    public ResultVo editPassword(@RequestBody ProfileEditPasswordParams params) throws IOException {
        if(params==null
                || StringUtils.isEmpty(params.getPassword())
                || StringUtils.isEmpty(params.getNewPassword())){
            return fail("参数异常");
        }

        User onlineUser = getOnline().getUser();
        User user = serviceManager.userService.getById(onlineUser.getId());

        String password = String.format("%s%s%s",projectConfig.getPasswordPrefix(),params.getPassword(),projectConfig.getPasswordSuffix());
        password = Md5.encrypt(password);

        if(!user.getPassword().equals(password)){
            return fail("密码错误");
        }

        String newPassword = String.format("%s%s%s",projectConfig.getPasswordPrefix(),params.getNewPassword(),projectConfig.getPasswordSuffix());
        newPassword = Md5.encrypt(newPassword);
        user.setPassword(newPassword);
        serviceManager.userService.updateById(user);

        return success();
    }

}
